package tgc.edu.ljc.bookmanage.web.controller;

import java.util.HashSet;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import tgc.edu.ljc.bookmanage.custom.CommonController;
import tgc.edu.ljc.bookmanage.entity.Student;
import tgc.edu.ljc.bookmanage.entity.TbClass;
import tgc.edu.ljc.bookmanage.service.StudentService;
import tgc.edu.ljc.bookmanage.web.form.StudentForm;

@Controller
@RequestMapping(value="/student")
public class StudentController extends CommonController<Student, Integer,StudentForm>{
	@Autowired
	private StudentService service;

	@Override
	public Specification<Student> buildSpec(StudentForm form) {
		Specification<Student> spec=new Specification<Student>() {

			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				String username = form.getUsername();
				if(StringUtils.hasText(username)) {
					rules.add(cb.like(root.get("username"), "%"+username+"%"));
				}
				String name = form.getName();
				if(StringUtils.hasText(name)) {
					rules.add(cb.like(root.get("name"), "%"+name+"%"));
				}
				TbClass tbClass = form.getTbClass();
				if(tbClass!=null&&tbClass.getId()!=null) {
					rules.add(cb.equal(root.get("tbClass").get("id"), tbClass.getId()));
				}
				String sex = form.getSex();
				if(StringUtils.hasText(sex)) {
					rules.add(cb.equal(root.get("sex"), sex));
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}

	
	
	
}
